package service4user

import (
	"Gin-Gorm-boke/boke_common/define"
	"Gin-Gorm-boke/boke_common/kafka"
	models2 "Gin-Gorm-boke/boke_common/models"
	"Gin-Gorm-boke/boke_common/response"
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/copier"
	"log"
	"strconv"
)

type HotArticleVO struct {
	Id        int    `json:"id"`
	Title     string `json:"title"`
	ViewCount int    `json:"viewCount"`
}
type ArticleListVo struct {
	Id           int            `json:"id"`
	Title        string         `json:"title"`
	Summary      string         `json:"summary"`
	CategoryName string         `json:"categoryName"`
	Thumbnail    string         `json:"thumbnail"`
	ViewCount    int            `json:"viewCount"`
	CreateTime   models2.MyTime `json:"createTime"`
}
type ArticleDetail struct {
	Id           int            `json:"id"`
	Title        string         `json:"title"`
	Content      string         `json:"content"`
	CategoryId   int            `json:"categoryId"`
	CategoryName string         `json:"categoryName"`
	ViewCount    int            `json:"viewCount"`
	IsComment    string         `json:"isComment"`
	CreateTime   models2.MyTime `json:"createTime"`
}

func GetHotArticleList(c *gin.Context) {
	var articleList []models2.Article
	err := models2.Db.Model(new(models2.Article)).
		Where("status=?", define.ARTICLE_STATUS_NORMAL).
		Order("view_count desc").
		Offset(0).Limit(10).
		Find(&articleList).Error
	if err != nil {
		response.ResponseInternalServerError(c)
		return
	}
	var hotArticleVOList []HotArticleVO
	copier.Copy(&hotArticleVOList, &articleList)
	response.ResponseOK(c, hotArticleVOList)
	return

}

func GetArticleList(c *gin.Context) {
	pageNum, err := strconv.Atoi(c.DefaultQuery("pageNum", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "10"))
	categoryId, _ := strconv.Atoi(c.Query("categoryId"))
	if err != nil {
		response.ResponseBadRequest(c)
	}
	var articleList []models2.Article
	var total int64
	db := models2.Db.Model(new(models2.Article)).
		Table("sg_article a").
		Select("a.*,c.name as category_name").
		Joins("LEFT JOIN sg_category c ON a.category_id = c.id")

	if categoryId != 0 {
		db.Where("a.category_id=?", categoryId)
	}

	db.Where("a.status=?", define.ARTICLE_STATUS_NORMAL).
		Count(&total).
		Order("created_at desc").
		Offset((pageNum - 1) * pageSize).
		Limit(pageSize).
		Find(&articleList)
	var articleListVoList []ArticleListVo
	copier.Copy(&articleListVoList, &articleList)
	response.ResponseOK(c, gin.H{
		"total": total,
		"rows":  articleListVoList,
	})
	return
}

func GetArticleById(c *gin.Context) {
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		response.ResponseBadRequest(c)
		return
	}
	var article models2.Article
	models2.Db.Model(new(models2.Article)).
		Table("sg_article a").
		Select("a.*,c.name as category_name").
		Joins("LEFT JOIN sg_category c ON a.category_id = c.id").
		Where("a.id=?", id).
		First(&article)
	var articleDetail ArticleDetail
	copier.Copy(&articleDetail, &article)
	response.ResponseOK(c, articleDetail)
	return

}

func UpdateViewCount(c *gin.Context) {
	id := c.Param("id")

	result, _ := models2.RDb.Exists(context.Background(), "article:viewCount").Result()
	if result > 0 {
		fmt.Println("Redis已存在map")
		models2.RDb.HIncrBy(context.Background(), "article:viewCount", id, 1)
	} else {
		fmt.Println("Redis不存在map")
		viewCountMap := map[int]int{}
		models2.RDb.HMSet(context.Background(), "article:viewCount", viewCountMap)
		models2.RDb.HIncrBy(context.Background(), "article:viewCount", id, 1)

	}
	response.ResponseOK(c, nil)
	return
}

func UpdateViewCountByKafka(c *gin.Context) {
	id := c.Param("id")
	response.ResponseOK(c, nil)

	go func() {
		err := kafka.ProduceMessage("article_viewCount", id)
		if err != nil {
			log.Printf("Failed to produce message: %v", err)
		}
	}()

	return
}
